/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2022/3/3 1:03:58
 *        Description: 暂无
 ***********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Caching.Manual;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.ViewModels.Basics;
using CoreCms.Net.IRepository;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.Model.ViewModels.UI;
using SqlSugar;

namespace CoreCms.Net.Repository
{
    /// <summary>
    /// 连续签到规则 接口实现
    /// </summary>
    public class CoreCmsContinuousCheckInRulesRepository : BaseRepository<CoreCmsContinuousCheckInRules>, ICoreCmsContinuousCheckInRulesRepository
    {
        private readonly IUnitOfWork _unitOfWork;
        public CoreCmsContinuousCheckInRulesRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }


        /// <summary>
        /// 重写异步插入方法
        /// </summary>
        /// <param name="entity">实体数据</param>
        /// <returns></returns>
        public async Task<AdminUiCallBack> InsertAsync(List<CoreCmsContinuousCheckInRules> entity)
        {
            var jm = new AdminUiCallBack();

            //判断是否存在0天数或者0赠送
            var isHaveEnptyDaysOrNum = entity.Count(p => p.days <= 0);
            if (isHaveEnptyDaysOrNum > 0)
            {
                jm.msg = "【连续签到天数】不能为零";
                return jm;
            }

            //判断是否存在相同的天数设置。
            var isHave = entity.GroupBy(i => i.days).Any(g => g.Count() > 1);
            if (isHave)
            {
                jm.msg = "存在相同的【连续签到天数】。请排查";
                return jm;
            }

            try
            {
                _unitOfWork.BeginTran();

                //先清理掉数据,因为是配置数据，可直接删除添加新的
                await DbClient.Deleteable<CoreCmsContinuousCheckInRules>().Where(p => p.id > 0).ExecuteCommandAsync();
                await DbClient.Deleteable<CoreCmsContinuousCheckInRuleDetails>().Where(p => p.id > 0).ExecuteCommandAsync();

                //遍历数据存值
                foreach (var item in entity)
                {
                    var continuous = new CoreCmsContinuousCheckInRules
                    {
                        days = item.days
                    };

                    var id = await DbClient.Insertable(continuous).ExecuteReturnIdentityAsync();
                    if (id <= 0) continue;
                    foreach (var detail in item.details)
                    {
                        detail.ruleId = id;
                    }
                    await DbClient.Insertable(item.details).ExecuteReturnIdentityAsync();
                }

                _unitOfWork.CommitTran();

                jm.code = 0;
                jm.msg = "更新成功";

            }
            catch (Exception e)
            {
                _unitOfWork.RollbackTran();
                jm.code = 1;
                jm.msg = "更新失败";
                jm.data = e;
            }
            return jm;
        }



        /// <summary>
        /// 获取的所有数据及子集
        /// </summary>
        /// <returns></returns>
        public async Task<List<CoreCmsContinuousCheckInRules>> GetDataWidthChild()
        {
            var list = await DbClient.Queryable<CoreCmsContinuousCheckInRules>()
                .Select(p => new CoreCmsContinuousCheckInRules
                {
                    id = p.id,
                    days = p.days,
                })
                .Mapper(p => p.details, p => p.details.First().ruleId)
                .With(SqlWith.NoLock).WithCache().ToListAsync();
            return list;
        }


    }
}
